import { logger } from '../utils/logger';
import prisma from '../lib/prisma';
import axios from 'axios';
import {
  HomeworkCriteria,
  HomeworkTemplate,
  HomeworkGenerationResponse,
  HomeworkTemplateResponse,
  HomeworkQuestion
} from '../types/aiHomework';

export class AIHomeworkGenerationService {
  private static readonly API_ENDPOINT = process.env.AI_HOMEWORK_GEN_API_URL;
  private static readonly API_KEY = process.env.AI_HOMEWORK_GEN_API_KEY;

  // 生成作业
  static async generateHomework(criteria: HomeworkCriteria) {
    try {
      // 调用AI服务生成作业内容
      const response = await axios.post<HomeworkGenerationResponse>(
        this.API_ENDPOINT as string,
        criteria,
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const { questions, template } = response.data;

      // 创建作业记录
      const homework = await prisma.homework.create({
        data: {
          title: template.title,
          description: template.description,
          subject: criteria.subject,
          gradeLevel: criteria.gradeLevel,
          difficulty: criteria.difficulty,
          estimatedDuration: criteria.estimatedDuration,
          questions: {
            create: questions.map((q: HomeworkQuestion) => ({
              title: q.title,
              content: q.content,
              type: q.type,
              difficulty: q.difficulty,
              choices: q.choices || [],
              correctAnswer: q.correctAnswer,
              explanation: q.explanation,
              points: q.points,
              aiGenerated: true
            }))
          },
          metadata: {
            criteria,
            template
          }
        }
      });

      logger.info('作业生成成功', {
        homeworkId: homework.id,
        criteria
      });

      return homework;
    } catch (error) {
      logger.error('作业生成失败', { error, criteria });
      throw new Error('作业生成失败，请稍后再试');
    }
  }

  // 根据知识点生成作业
  static async generateByKnowledgePoints(
    knowledgePoints: string[],
    criteria: Omit<HomeworkCriteria, 'topics'>
  ) {
    try {
      // 调用AI服务根据知识点生成作业
      const response = await axios.post<HomeworkGenerationResponse>(
        `${this.API_ENDPOINT}/knowledge-points` as string,
        {
          knowledgePoints,
          ...criteria
        },
        {
          headers: {
            'Authorization': `Bearer ${this.API_KEY}`,
            'Content-Type': 'application/json'
          }
        }
      );

      const { questions, template } = response.data;

      // 创建作业记录
      const homework = await prisma.homework.create({
        data: {
          title: template.title,
          description: template.description,
          subject: criteria.subject,
          gradeLevel: criteria.gradeLevel,
          difficulty: criteria.difficulty,
          estimatedDuration: criteria.estimatedDuration,
          questions: {
            create: questions.map((q: HomeworkQuestion) => ({
              title: q.title,
              content: q.content,
              type: q.type,
              difficulty: q.difficulty,
              choices: q.choices || [],
              correctAnswer: q.correctAnswer,
              explanation: q.explanation,
              points: q.points,
              aiGenerated: true,
              knowledgePoints: q.knowledgePoints
            }))
          },
          metadata: {
            criteria: {
              ...criteria,
              knowledgePoints
            },
            template
          }
        }
      });

      logger.info('基于知识点生成作业成功', {
        homeworkId: homework.id,
        knowledgePoints
      });

      return homework;
    } catch (error) {
      logger.error('基于知识点生成作业失败', {
        error,
        knowledgePoints,
        criteria
      });
      throw new Error('作业生成失败，请稍后再试');
    }
  }

  // 获取作业模板
  static async getHomeworkTemplates(subject: string, gradeLevel: number) {
    try {
      // 从数据库获取预定义模板
      const templates = await prisma.homeworkTemplate.findMany({
        where: {
          subject,
          gradeLevel,
          status: 'ACTIVE'
        }
      });

      // 如果没有足够的模板，使用AI生成新模板
      if (templates.length < 3) {
        const response = await axios.post<HomeworkTemplateResponse>(
          `${this.API_ENDPOINT}/templates` as string,
          {
            subject,
            gradeLevel
          },
          {
            headers: {
              'Authorization': `Bearer ${this.API_KEY}`,
              'Content-Type': 'application/json'
            }
          }
        );

        // 保存新生成的模板
        await prisma.homeworkTemplate.createMany({
          data: response.data.templates.map((t: HomeworkTemplate) => ({
            ...t,
            subject,
            gradeLevel,
            status: 'ACTIVE',
            aiGenerated: true
          }))
        });

        return [...templates, ...response.data.templates];
      }

      return templates;
    } catch (error) {
      logger.error('获取作业模板失败', { error, subject, gradeLevel });
      throw new Error('获取作业模板失败，请稍后再试');
    }
  }

  // 根据模板生成作业
  static async generateFromTemplate(templateId: string, customizations: Partial<HomeworkCriteria>) {
    try {
      // 获取模板信息
      const template = await prisma.homeworkTemplate.findUnique({
        where: { id: templateId }
      });

      if (!template) {
        throw new Error('作业模板不存在');
      }

      // 合并模板和自定义设置
      const mergedCriteria = {
        ...template.defaultCriteria,
        ...customizations
      } as HomeworkCriteria;

      // 生成作业
      return this.generateHomework(mergedCriteria);
    } catch (error) {
      logger.error('根据模板生成作业失败', {
        error,
        templateId,
        customizations
      });
      throw new Error('根据模板生成作业失败，请稍后再试');
    }
  }
}
